﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using $ext_safeprojectname$.redismodel;
using $ext_safeprojectname$.usermodels;
using Volo.Abp;

namespace $ext_safeprojectname$
{
    /// <summary>
    /// 这里的权限筛选器
    /// </summary>
    public class RoleAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 权限
        /// </summary>
        private string _role { set; get; }

        /// <summary>
        /// 角色
        /// </summary>
        private string _model { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private readonly ModelHelper _appCache;

        /// <summary>
        /// 
        /// </summary>
        private readonly IServiceProvider _serviceProvider;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="appcache"></param>
        /// <param name="serviceProvider"></param>
        /// <param name="Model"></param>
        /// <param name="Role"></param>
        public RoleAttribute(
            ModelHelper appcache,
            IServiceProvider serviceProvider,
            string Model = default,
            string Role = default
            )
        {
            _serviceProvider = serviceProvider;
            _role = Role;
            _model = Model;
            //_redisClient = redisClient;
            _appCache = appcache;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="$ext_safeprojectname$Exception"></exception>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //authorization
            if (context.HttpContext.Request.Headers[PublicString.TokenHeadName].Count == 0)
            {
                throw new $ext_safeprojectname$Exception("当前未登录，请登录后重试", "401");
            }
            var token = context.HttpContext.Request.Headers[PublicString.TokenHeadName].ToString();
            if (token.StartsWith("Bearer"))
            {
                token = token.Replace("Bearer ", "");
            }

            //这里可以做token的安全校验

            if (!String.IsNullOrEmpty(token))
            {

                var back = _appCache.HasRole(_model,_role,token);
                if (!back.role)
                {
                    throw new $ext_safeprojectname$Exception($"{(back.code==401?"当前登录密钥失效，请重新登录":"没有当前接口的操作权限，请确认")}", $"{back.code}");
                }
            }
            else
            {
                throw new $ext_safeprojectname$Exception("当前密钥信息有误，请登录后重试", "401");
            }
            base.OnActionExecuting(context);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class ExceptionModel
    {
        /// <summary>
        /// 
        /// </summary>
        public string code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public bool success { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string message { get; set; }
    }

    /// <summary>
    /// 自定义全局错误处理，使用错误代码httpstatuscode
    /// </summary>
    public class PlanExceptionAttribute : ExceptionFilterAttribute
    {

        private readonly ILogger<PlanExceptionAttribute> _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public PlanExceptionAttribute(ILogger<PlanExceptionAttribute> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                var info = new ExceptionModel();
                info.code = "500";
                info.success = false;
                info.message = context.Exception.Message;
                if (context.Exception.InnerException != null)
                {
                    if (context.Exception.InnerException is $ext_safeprojectname$Exception)
                    {
                        var _customException = context.Exception.InnerException as $ext_safeprojectname$Exception;
                        if (_customException != null)
                        {
                            info.code = $"{_customException.Code}";
                        }
                    }
                    else if (context.Exception.InnerException is UserFriendlyException)
                    {
                        var _uriexception = context.Exception.InnerException as UserFriendlyException;
                        if (_uriexception != null)
                        {
                            info.code = $"{_uriexception.Code}";
                        }
                    }
                }
                else
                {
                    if (context.Exception is $ext_safeprojectname$Exception)
                    {
                        var _customException = context.Exception as $ext_safeprojectname$Exception;
                        if (_customException != null)
                        {
                            info.code = $"{_customException.Code}";
                        }
                    }
                    else if (context.Exception is UserFriendlyException)
                    {
                        var _uriexception = context.Exception as UserFriendlyException;
                        if (_uriexception != null)
                        {
                            info.code = $"{_uriexception.Code}";
                        }
                    }
                }
                if (context.ModelState != null)
                {
                    if (context.ModelState.Count > 0)
                    {
                        foreach (var key in context.ModelState.Keys)
                        {
                            context.ModelState.TryGetValue(key, out var val);
                            if (val.Errors.Count > 0)
                            {
                                info.message = key + "::" + val.Errors[0].ErrorMessage;
                                info.code="400";
                                break;
                            }
                        }
                    }
                }
                if (info.code == "500")
                {
                    _logger.LogError(context.Exception.InnerException != null ? context.Exception.InnerException : context.Exception, context.HttpContext.Request.Path, null);
                }
                context.Result = new ContentResult
                {
                    StatusCode = int.Parse(info.code),
                    ContentType = "application/json;charset=utf-8",
                    Content = Newtonsoft.Json.JsonConvert.SerializeObject(info)
                };
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override System.Threading.Tasks.Task OnExceptionAsync(ExceptionContext context)
        {
            return base.OnExceptionAsync(context);
        }
    }

}
